package com.vitria.m3oui.rest.app.mgr;

import java.util.ArrayList;
import java.util.List;

import junit.framework.TestCase;

import org.apache.http.NameValuePair;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class PXUpgradeTest  extends TestCase{
		
	private static DefaultHttpClient httpclient = null;
		
	@Override
	public void setUp(){
		if(httpclient == null)
			httpclient = HttpClient.login("vtbaadmin", "vitria");
	}
	
	@Override
	public void tearDown(){
	}

	
	private ArrayList<String> listRunningModels(){
		String opString = "/m3oui/rest/app.mgr/apps/px?op=list.models&status=Running";
		String response = HttpClient.get(httpclient, opString);
		ArrayList<String> models = new ArrayList<String>();
		try {
			Document dom = DocumentHelper.parseText(response);
			Element root = dom.getRootElement();
			List<Element> elements = root.elements("model");
			for(Element ele:elements){
				models.add(ele.attributeValue("id"));
			}
		} catch (DocumentException e) {			
			e.printStackTrace();
		}
		return models;
	}
	
	private void operateModel(String opt, String id){
		String opString = "/m3oui/rest/app.mgr/apps/px?op="+opt+".model";
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("id", id)); 
		HttpClient.post(httpclient, opString, params);
	}
	
	private void upgradeApp(String uid){
		String opString = "/m3oui/rest/app.mgr/apps/px?op=upgrade&uid="+uid;
		HttpClient.get(httpclient, opString);
	}
	
	public void testPDUpgrade(){
		int count = 20;
		ArrayList<String> models = listRunningModels();
		
		for(int i=0; i<count; i++){
			//stop px model
			for(String model:models)
				operateModel("stop", model);
			
			//upgrade px app
			upgradeApp(i%2==0?"px.2.0.zip":"px.1.0.zip");
	
			//start px model
			for(String model:models)
				operateModel("start", model);
			
		}
	}
}
